import { useCallback, useEffect, useState } from 'react';
import {
  Table,
  Button,
  Input,
  Modal,
  Form,
  message,
  Popconfirm,
  Space,
  Card,
  Typography,
} from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { addUserApi, deleteUserApi, getUserListApi, updateUserInfoApi } from '@/api/user';

interface UserInfo {
  id: number;
  user_name: string;
  password: string;
  phone: string;
  created_time: string;
}

/**
 * 用户管理界面
 */
const User = () => {
  const [form] = Form.useForm();
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [searchText, setSearchText] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserInfo | null>(null);

  // 获取用户列表
  const fetchUsers = async () => {
    const res = await getUserListApi();
    setUsers(res.data);
  };

  // 页面加载时获取用户列表
  useEffect(() => {
    fetchUsers();
  }, []);

  // 创建用户
  const createUser = async (values: Omit<UserData['userInfo'], 'id' | 'created_time'>) => {
    addUserApi(values).then((res) => {
      if (res.code === 200) {
        message.success('创建成功');
        fetchUsers();
      } else {
        message.error('创建失败');
      }
    });
  };

  // 更新用户
  const updateUser = async (values: UpdateUserInfoForm) => {
    if (!editingUser) return;
    updateUserInfoApi({ ...values, id: editingUser.id }).then((res) => {
      if (res.code === 200) {
        message.success('更新成功');
        fetchUsers();
      } else {
        message.error('更新失败');
      }
    });
  };

  // 新增用户
  const handleAdd = (values: Omit<UserData['userInfo'], 'id' | 'created_time'>) => {
    createUser(values);
  };

  const handleEdit = (values: UpdateUserInfoForm) => {
    if (!editingUser) return;
    updateUser(values);
  };

  const handleDelete = (id: number) => {
    deleteUserApi(id).then((res) => {
      if (res.code === 200) {
        message.success('删除成功');
        fetchUsers();
      } else {
        message.error('删除失败');
      }
    });
  };

  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    // 如果需要后端搜索，这里可以调用 fetchUsers 并传入搜索参数
  }, []);

  // 显示编辑用户弹窗
  const showModal = (user?: UserInfo) => {
    if (user) {
      // 设置正在编辑的用户
      setEditingUser(user);
      // 设置表单的值
      form.setFieldsValue(user);
    } else {
      // 清空正在编辑的用户
      setEditingUser(null);
      // 清空表单
      form.resetFields();
    }
    // 显示弹窗
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (editingUser) {
        // 更新用户
        handleEdit(values);
      } else {
        // 新增用户
        handleAdd(values);
      }
      // 关闭弹窗
      setIsModalVisible(false);
      // 清空表单
      form.resetFields();
    });
  };

  const columns: ColumnsType<UserInfo> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '用户名',
      dataIndex: 'user_name',
      key: 'user_name',
      width: 150,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'created_time',
      key: 'created_time',
      render: (created_time) => {
        return new Date(created_time).toLocaleString();
      },
      width: 200,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const filteredUsers = users.filter(
    (user) =>
      user.user_name.toLowerCase().includes(searchText.toLowerCase()) ||
      user.phone.includes(searchText)
  );

  return (
    <div className="p-6">
      <Card>
        <div className="flex justify-between items-center mb-4">
          <Typography.Title
            level={2}
            className="!mb-0"
          >
            用户管理
          </Typography.Title>
          <Space>
            <Input
              placeholder="搜索用户名或手机号"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => handleSearch(e.target.value)}
              allowClear
              style={{ width: 200 }}
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
            >
              新增用户
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />

        <Modal
          title={editingUser ? '编辑用户' : <span>新增用户</span>}
          open={isModalVisible}
          onOk={handleModalOk}
          onCancel={() => {
            setIsModalVisible(false);
            form.resetFields();
          }}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
          >
            <Form.Item
              name="user_name"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="phone"
              label="手机号"
              rules={[{ required: !editingUser, message: '请输入手机号' }]}
            >
              <Input disabled={!!editingUser} />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default User;
